package weaver.hrm.company;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.cache.CacheBase;
import weaver.cache.CacheColumn;
import weaver.cache.CacheColumnType;
import weaver.cache.CacheItem;
import org.apache.commons.lang3.StringUtils;
import weaver.cache.CacheMap;
import weaver.cache.PKColumn;
import weaver.conn.*;
import weaver.general.*;
import weaver.hrm.cachecenter.bean.SuperDepartmentComInfo;
import weaver.hrm.cachecenter.bean.LoadComInfo;
import weaver.hrm.common.database.dialect.DbDialectFactory;
import weaver.hrm.common.database.dialect.DialectUtil;
import weaver.hrm.companyvirtual.DepartmentVirtualComInfo;

/**
 * 部门缓存类
 */
public class DepartmentComInfo extends CacheBase {
    //需要定义的信息 begin
    protected static String TABLE_NAME = "HrmDepartment";
    /**
     * sql中的where信息，不要以where开始
     */
    protected static String TABLE_WHERE = null;
    /**
     * sql中的order by信息，不要以order by开始
     */
    protected static String TABLE_ORDER = "subcompanyid1 asc , supdepid asc , showorder asc, departmentname asc ";

    @PKColumn(type = CacheColumnType.NUMBER)
    protected static String PK_NAME = "id";
    @CacheColumn(name = "departmentname")
    protected static int name;//账号
    @CacheColumn(name = "departmentmark")
    protected static int mark;
    @CacheColumn(name = "supdepid")
    protected static int supdepid;
    @CacheColumn(name = "allsupdepid")
    protected static int allsupdepid;
    @CacheColumn(name = "subcompanyid1")
    protected static int subcompanyid1;
    @CacheColumn(name = "showorder")
    protected static int showorder;
    @CacheColumn(name = "canceled")
    protected static int canceled;
    @CacheColumn(name = "coadjutant")
    protected static int coadjutant;
    @CacheColumn(name = "departmentcode")
    private static int departmentcode;

    private static ConcurrentHashMap<String, String> id2Idx = new ConcurrentHashMap<String, String>();
    private static ConcurrentHashMap<String, String> idx2Id = new ConcurrentHashMap<String, String>();
    private static ConcurrentHashMap<String, String> id2ParentIds = new ConcurrentHashMap<String, String>();
    private static ConcurrentHashMap<String, String> id2ChildIds = new ConcurrentHashMap<String, String>();

    //需要定义的信息 end

    public CacheMap initCache() throws Exception {
        CacheMap localData = super.createCacheMap();
        int idx = 0;
        id2Idx.clear();
        idx2Id.clear();
        RecordSet rs = new RecordSet();
        rs.executeProc("HrmDepartment_Select", "");
        while (rs.next()) {
            String id = Util.null2String(rs.getString(PK_NAME));
            CacheItem row = createCacheItem();
            parseResultSetToCacheItem(rs, row);

            // 这里需要记得调用这个 转化方法， 否则 这些自己加载的数据就不能正确转化，当然你也可以直接在转化逻辑写在这里，不过这样先让代码重复了
            modifyCacheItem(id, row);
            localData.put(id, row);
            id2Idx.put(rs.getString("id"), "" + idx);
            idx2Id.put("" + idx, rs.getString("id"));
            idx++;
        }
        return localData;
    }

    public CacheItem initCache(String key) {
        return null;
    }

    /**
     * 获取缓存记录数目
     *
     * @return
     */
    public int getCompanyNum() {
        return size();
    }

    /**
     * 获取部门id
     *
     * @return
     */
    public String getDepartmentid() {
        return (String) getRowValue(PK_INDEX);
    }

    /**
     * 通过index获取部门的id
     *
     * @param key
     * @return
     */
    public String getDepartmentid(int key) {
        return idx2Id.get("" + key);
    }

    /**
     * 获取部门编号
     *
     * @return
     */
    public String getDepartmentCode() {
        return (String) getRowValue(departmentcode);
    }

    /**
     * 根据关键字获取部门编号
     *
     * @param key
     * @return
     */
    public String getDepartmentCode(String key) {
        if (Util.getIntValue(key) < 0) {
            //取多维组织
            try {
                DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo();
                return DepartmentVirtualComInfo.getDepartmentCode(key);
            } catch (Exception e) {
                writeLog(e);
            }
        }
        return (String) getValue(departmentcode, key);
    }

    /**
     * 由关键字获取部门的index
     *
     * @param key 关键字
     * @return
     */
    public int getIdIndexKey(String key) {
        return Util.getIntValue(id2Idx.get(key));
    }

    /**
     * 获取部门名称
     *
     * @return
     */
    public String getDepartmentname() {
        return ((String) (getRowValue(name)));
    }

    /**
     * 由关键字获取部门名称
     *
     * @param key 关键字
     * @return
     */
    public String getDepartmentname(String key) {
        if (Util.getIntValue(key) < 0) {
            //取多维组织
            try {
                DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo();
                return DepartmentVirtualComInfo.getDepartmentname(key);
            } catch (Exception e) {
                writeLog(e);
            }
        }
        return (String) getValue(name, key);
    }

    /**
     * 由关键字获取部门名称
     *
     * @param key 关键字
     * @return
     */
    public String getDepartmentnameToLink(String key) {
        return "<a href=\"/hrm/company/HrmDepartmentDsp.jsp?id=" + key + "\" target=\"_new\"  >" + getDepartmentname(key) + "</a>";
    }

    /**
     * 获取部门简称
     *
     * @return
     */
    public String getDepartmentmark() {
        return ((String) (getRowValue(mark)));
    }

    /**
     * 由关键字获取部门简称
     *
     * @param key 关键字
     * @return
     */
    public String getDepartmentmark(String key) {
        if (Util.getIntValue(key) < 0) {
            //取多维组织
            try {
                DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo();
                return DepartmentVirtualComInfo.getDepartmentmark(key);
            } catch (Exception e) {
                writeLog(e);
            }
        }

        return (String) getValue(mark, key);
    }

    /**
     * 获取上级部门id
     *
     * @return
     */
    public String getDepartmentsupdepid() {
        return (String) (getRowValue(supdepid));
    }

    /**
     * 由关键字获取上级部门id
     *
     * @param key 关键字
     * @return
     */
    public String getDepartmentsupdepid(String key) {
        return (String) getValue(supdepid, key);
    }

    /**
     * 获取协办人
     *
     * @return
     */
    public String getCoadjutant() {
        return (String) (getRowValue(coadjutant));
    }

    /**
     * 由关键字获取协办人
     *
     * @param key 关键字
     * @return
     */
    public String getCoadjutant(String key) {
        return (String) getValue(coadjutant, key);
    }

    /**
     * 获取所有上级部门id （此方法已禁用）
     *
     * @return
     */
    public String getAllsupdepid() {
        return (String) getRowValue(allsupdepid);
    }

    /**
     * 由关键字获取所有上级部门id  （此方法已禁用）
     *
     * @param key
     * @return
     */
    public String getAllsupdepid(String key) {
        return (String) getValue(allsupdepid, key);
    }

    /**
     * 获取显示顺序
     *
     * @return
     */
    public String getShoworder() {
        return (String) getRowValue(showorder);
    }

    /**
     * 由关键字获取显示顺序
     *
     * @param key 关键字
     * @return
     */
    public String getShoworder(String key) {
        return (String) getValue(showorder, key);
    }

    /**
     * 获取分部id
     *
     * @return
     */
    public String getSubcompanyid1() {
        return (String) getRowValue(subcompanyid1);
    }

    /**
     * 由关键字获取分部id
     *
     * @param key 关键字
     * @return
     */
    public String getSubcompanyid1(String key) {
        return (String) getValue(subcompanyid1, key);
    }

    /**
     * 获取分部封存信息
     *
     * @return
     */
    public String getDeparmentcanceled() {
        return (String) getRowValue(canceled);
    }

    /**
     * 由关键字获取分部封存信息
     *
     * @param key 关键字
     * @return
     */
    public String getDeparmentcanceled(String key) {
        return (String) getValue(canceled, key);
    }


    /**
     * 删除缓存数据
     */
    public void removeCompanyCache() {
        new SuperDepartmentComInfo().removeCache();
        super.removeCache();
        id2ChildIds.clear();
        id2ParentIds.clear();
    }

    /**
     * 获取所有上级部门id（此方法已禁用）
     *
     * @param depid
     * @return
     */
    public String getAllSupDepId(int depid) {
        RecordSet rs = new RecordSet();
        String allsupdepid = "";
        int supdepid = 0;
        String sql = "select supdepid from HrmDepartment where id = " + depid;
        rs.executeSql(sql);
        while (rs.next()) {
            supdepid = Util.getIntValue(rs.getString("supdepid"), 0);
        }
        sql = "select allsupdepid from HrmDepartment where id = " + supdepid;
        rs.executeSql(sql);
        while (rs.next()) {
            allsupdepid = rs.getString("allsupdepid");
        }
        allsupdepid = allsupdepid + supdepid + ",";

        return allsupdepid;
    }

    public int getLevelByDepId(String depId) {
        RecordSet rs = new RecordSet();
        int level1 = 0;
        int level2 = 0;
        int result = 0;
        String supdepid = "0";
        String subcompanyid = "0";
        String sql = "select subcompanyid1,supdepid from HrmDepartment where id = " + depId;
        rs.executeSql(sql);
        if (rs.next()) {
            supdepid = Util.null2String(rs.getString(2));
            subcompanyid = Util.null2String(rs.getString(1));
            level1++;
            level2++;
            if ("".equals(supdepid))
                supdepid = "0";
            if ("".equals(subcompanyid))
                subcompanyid = "0";
        }
        while (!"0".equals(supdepid)) {
            sql = "select supdepid from HrmDepartment where id = " + supdepid;
            rs.executeSql(sql);
            if (rs.next()) {
                supdepid = Util.null2String(rs.getString(1));
                level1++;
                if ("".equals(supdepid)) {
                    supdepid = "0";
                }
            } else {
                break;
            }
        }
        while (!"0".equals(subcompanyid)) {
            sql = "select supsubcomid from HrmSubCompany where id = " + subcompanyid;
            rs.executeSql(sql);
            if (rs.next()) {
                subcompanyid = Util.null2String(rs.getString(1));
                level2++;
                if ("".equals(subcompanyid)) {
                    subcompanyid = "0";
                }
            } else {
                break;
            }
        }
        result = level1 + level2;
        return result;
    }

    public String getDeptnames(String deptids) {
        String returnStr = "";
        String[] arr = Util.TokenizerString2(deptids, ",");
        for (int i = 0; i < arr.length; i++) {
            returnStr += getDepartmentname(arr[i]) + ",";
        }
        if (!"".equals(returnStr)) returnStr = returnStr.substring(0, returnStr.length() - 1);
        return returnStr;
    }

    public ArrayList getAllChildDeptByDepId(ArrayList childDept, String depId) {
        RecordSet rs = new RecordSet();
        rs.executeSql("select id from HrmDepartment where supdepid=" + depId);
        while (rs.next()) {
            String childdepartmenttmp = Util.null2String(rs.getString(1));
            if ("".equals(childdepartmenttmp)) {
                continue;
            }
            childDept.add(childdepartmenttmp);
            getAllChildDeptByDepId(childDept, childdepartmenttmp);
        }
        return childDept;
    }

    public String getChildDeptId(String depId) {
        String id = null;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from HrmDepartment where supdepid = ?", depId);
        while (rs.next()) {
            id = Util.null2String(rs.getString(1));
        }
        return id;
    }

    /**
     * @param deptid
     * @param ids
     * @return
     * @throws Exception
     * @deprecated
     */
    public static String getAllParentDepartIdbak(String deptid, String ids) throws Exception {
        RecordSet rs_s = new RecordSet();
        rs_s.executeSql("select supdepid from HrmDepartment where (canceled IS NULL OR canceled !='1') and supdepid !=0 and id = " + deptid);
        while (rs_s.next()) {
            ids += "," + rs_s.getString(1);
            ids = getAllParentDepartIdbak(rs_s.getString(1), ids);
        }
        return ids;
    }

    /**
     * 获取所有父节点
     *
     * @param depId 部门id
     * @return
     * @throws Exception
     */
    public String getAllSupDepartment(String depId) throws Exception {
        if (id2ParentIds.containsKey(depId)) {
            return id2ParentIds.get(depId);
        }
        String tmpIds = getAllSupDepartment(depId, new DepartmentComInfo(), 1);
        id2ParentIds.put(depId, tmpIds);
        return tmpIds;
    }

    private String getAllSupDepartment(String subId, DepartmentComInfo rs, int loopLevel) throws Exception {
        String str = "";
        if (rs == null) {
            rs = new DepartmentComInfo();
        }
        String depid = rs.getDepartmentsupdepid(subId);
        if (depid == null || depid.equals("") || depid.equals("0") || depid.equals(subId)
                || ("," + str).indexOf("," + depid + ",") > -1 || loopLevel > 10000)
            return str;
        str += depid + ",";
        loopLevel++;
        str += getAllSupDepartment(depid, rs, loopLevel);
        return str;
    }

    public static String getAllParentDepartId(String deptid, String ids) throws Exception {
//  	StringBuffer sql = new StringBuffer();
//  	RecordSet rs = new RecordSet();
//  	String dbType = rs.getDBType();
//  	if("oracle".equalsIgnoreCase(dbType)){
//  		sql.setLength(0);
//  		sql.append(" select id, departmentname, supdepid, subcompanyid1 ").
//  		append("   from hrmdepartment                                      ").
//  		append("  where (canceled != 1 or canceled is null)                ").
//  		append("  start with id = '").append(deptid).append("'").
//  		append(" connect by prior supdepid = id                         ");
//  	}else if("sqlserver".equalsIgnoreCase(dbType)){
//  		sql.setLength(0);
//  		sql.append(" WITH allsub(id,departmentname,supdepid,subcompanyid1)").
//  		append(" as ( SELECT id,departmentname ,supdepid,subcompanyid1 FROM hrmdepartment where id=").append(deptid).append("  and (canceled  !=1 or canceled is null)").
//  		append(" UNION ALL SELECT a.id,a.departmentname,a.supdepid,a.subcompanyid1 FROM hrmdepartment a,allsub b where a.id=b.supdepid and (canceled  !=1 or canceled is null)").
//  		append(" ) select * from allsub  ");
//  	}
//  	rs.executeSql(sql.toString());
//  	while(rs.next()){
//  		String depart = rs.getString("id");
//  		if(depart.equals(deptid))continue;
//  		ids += ","+ depart;
//  	}
//  	System.out.println("ids=="+ids);
        try {
            String allids = new DepartmentComInfo().getAllSupDepartment(deptid);
            if (allids.length() > 0) {
                ids += "," + allids;
                if (ids.endsWith(",")) ids = ids.substring(0, ids.lastIndexOf(","));
            }
        } catch (Exception e) {
            new BaseBean().writeLog("SubCompanyComInfo>>>getAllParentSubcompanyId" + e);
        }
        return ids;
    }

    /**
     * @param deptid
     * @param ids
     * @return
     * @throws Exception
     * @deprecated
     */
    public static String getAllChildDepartIdbak(String deptid, String ids) throws Exception {
        RecordSet rs_s = new RecordSet();
        rs_s.executeSql("select id from HrmDepartment where (canceled IS NULL OR canceled !='1') and id <>  " + deptid + " and supdepid = " + deptid);
        while (rs_s.next()) {
            ids += "," + rs_s.getString(1);
            ids = getAllChildDepartIdbak(rs_s.getString(1), ids);
        }
        return ids;
    }

    /**
     * @param deptid
     * @param ids
     * @return
     * @throws Exception
     */
    public static String getAllChildDepartId(String deptid, String ids) throws Exception {
        return getAllChildDepartId(deptid, ids, false);
    }

    /**
     * @param deptid
     * @param ids
     * @param containsCancel 是否包含封存部门
     * @return
     * @throws Exception
     */
    public static String getAllChildDepartId(String deptid, String ids, boolean containsCancel) throws Exception {

        SuperDepartmentComInfo superDepartmentComInfo = LoadComInfo.getInstance(SuperDepartmentComInfo.class);
        String allDownIds = superDepartmentComInfo.getAllDownIdsBySuperId(deptid, containsCancel);
        if (StringUtils.isNotBlank(allDownIds)) {
            ids += "," + allDownIds;
        }
        return ids;
    }

    /**
     * 获取分部和部门所属关系的纯名称显示
     * 分部与部门之间用||
     * 分部层级，部门层级之间用>
     *
     * @param deptid
     * @param subcomid
     * @return
     * @throws Exception
     */
    public String getAllParentDepartmentBlankNames(String deptid, String subcomid) throws Exception {
        String returnStr = "";
        String subReturnStr = "";
        String deptReturnStr = "";
        String subcompanyid = this.getSubcompanyid1(deptid);
        if (subcompanyid.length() == 0) subcompanyid = subcomid;
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String psubComids = "";
        psubComids = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid, psubComids);
        psubComids = subcompanyid + psubComids;
        String[] arr = Util.TokenizerString2(psubComids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(subCompanyComInfo.getSubcompanyname(arr[i])).length() == 0) continue;
            if (subReturnStr.length() > 0) subReturnStr += ">";
            subReturnStr += subCompanyComInfo.getSubcompanyname(arr[i]);
        }

        String pdeptids = "";
        pdeptids = getAllParentDepartId(deptid, pdeptids);
        pdeptids = deptid + pdeptids;
        arr = Util.TokenizerString2(pdeptids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(getDepartmentname(arr[i])).length() == 0) continue;
            if (deptReturnStr.length() > 0) deptReturnStr += ">";
            deptReturnStr += getDepartmentname(arr[i]);
        }
        if (subReturnStr.length() > 0 && deptReturnStr.length() > 0) {
            returnStr = subReturnStr + "||" + deptReturnStr;
        }

        return returnStr;
    }

    /**
     * create by Eugene 2019.3.8
     * 获取组织全路径，根据delimiter格式化
     *
     * @param deptid
     * @param delimiter
     * @return
     * @throws Exception
     */
    public String getAllParentDepartmentBlankNames(String deptid, String subcomid, String delimiter) throws Exception {
        String returnStr = "";
        String subReturnStr = "";
        String deptReturnStr = "";
        String subcompanyid = this.getSubcompanyid1(deptid);
        if (subcompanyid.length() == 0) subcompanyid = subcomid;
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String psubComids = "";
        psubComids = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid, psubComids);
        psubComids = subcompanyid + psubComids;
        String[] arr = Util.TokenizerString2(psubComids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(subCompanyComInfo.getSubcompanyname(arr[i])).length() == 0) continue;
            if (subReturnStr.length() > 0) subReturnStr += delimiter;
            subReturnStr += subCompanyComInfo.getSubcompanyname(arr[i]);
        }

        String pdeptids = "";
        pdeptids = getAllParentDepartId(deptid, pdeptids);
        pdeptids = deptid + pdeptids;
        arr = Util.TokenizerString2(pdeptids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(getDepartmentname(arr[i])).length() == 0) continue;
            if (deptReturnStr.length() > 0) deptReturnStr += delimiter;
            deptReturnStr += getDepartmentname(arr[i]);
        }
        if (subReturnStr.length() > 0 && deptReturnStr.length() > 0) {
            returnStr = subReturnStr + delimiter + deptReturnStr;
        }

        return returnStr;
    }

    public String getAllParentDepartmentBlankNames(String deptid, String subcomid, String delimiter, String orderType, boolean includeSelf) throws Exception {
        List<String> infoList = new ArrayList<>();
        String subcompanyid = this.getSubcompanyid1(deptid);
        if (subcompanyid.length() == 0) subcompanyid = subcomid;
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String psubComids = "";
        psubComids = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid, psubComids);
        psubComids = subcompanyid + psubComids;
        String[] arr = Util.TokenizerString2(psubComids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(subCompanyComInfo.getSubcompanyname(arr[i])).length() == 0) continue;
            infoList.add(subCompanyComInfo.getSubcompanyname(arr[i]));
        }

        String pdeptids = "";
        pdeptids = getAllParentDepartId(deptid, pdeptids);
        pdeptids = deptid + pdeptids;
        arr = Util.TokenizerString2(pdeptids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(getDepartmentname(arr[i])).length() == 0 || (!includeSelf && arr[i].equals(deptid)))
                continue;
            infoList.add(getDepartmentname(arr[i]));
        }
        if ("".equals(orderType) || "0".equals(orderType))
            return String.join(delimiter, infoList);
        else {
            Collections.reverse(infoList);
            return String.join(delimiter, infoList);
        }
    }

    public String getAllParentDepartmentNames(String deptid, String subcomid) throws Exception {
        String returnStr = "";
        String subcompanyid = this.getSubcompanyid1(deptid);
        if (subcompanyid.length() == 0) subcompanyid = subcomid;
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String psubComids = "";
        psubComids = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid, psubComids);
        psubComids = subcompanyid + psubComids;
        String[] arr = Util.TokenizerString2(psubComids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(subCompanyComInfo.getSubCompanydesc(arr[i])).length() == 0) continue;
            if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
            returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewSubCompany(" + arr[i] + ");\" >" +
                    subCompanyComInfo.getSubCompanydesc(arr[i]) + "</a>";
        }

        String pdeptids = "";
        pdeptids = getAllParentDepartId(deptid, pdeptids);
        pdeptids = deptid + pdeptids;
        arr = Util.TokenizerString2(pdeptids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(getDepartmentname(arr[i])).length() == 0) continue;
            if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
            returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewDepartment(" + arr[i] + ");\" >" +
                    getDepartmentname(arr[i]) + "</a>";
        }

        return returnStr;
    }

    /**
     * 顺胜-获取人员组织路径（分部/.../部门）
     *
     * @param deptid
     * @param subcomid
     * @return
     * @throws Exception
     */
    public String getSSAllParentDepartmentNames(String deptid, String subcomid) throws Exception {
        String returnStr = "";
        String subcompanyid = this.getSubcompanyid1(deptid);
        if (subcompanyid.length() == 0) subcompanyid = subcomid;
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String psubComids = "";
        psubComids = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid, psubComids);
        psubComids = subcompanyid + psubComids;
        String[] arr = Util.TokenizerString2(psubComids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(subCompanyComInfo.getSubCompanydesc(arr[i])).length() == 0) continue;

            if (i == arr.length - 1) {
                if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
                returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewSubCompany(" + arr[i] + ");\" >" +
                        subCompanyComInfo.getSubCompanydesc(arr[i]) + "</a>";
            }

        }

        String pdeptids = "";
        pdeptids = getAllParentDepartId(deptid, pdeptids);
        pdeptids = deptid + pdeptids;
        arr = Util.TokenizerString2(pdeptids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(getDepartmentname(arr[i])).length() == 0) continue;

            if (i == 0) {
                if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
                returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewDepartment(" + arr[i] + ");\" >" +
                        getDepartmentname(arr[i]) + "</a>";
            }
        }

        return returnStr;
    }

    public String getAllParentDepartmentMarks(String deptid, String subcomid) throws Exception {
        String returnStr = "";
        String subcompanyid = this.getSubcompanyid1(deptid);
        if (subcompanyid.length() == 0) subcompanyid = subcomid;
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String psubComids = "";
        psubComids = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid, psubComids);
        psubComids = subcompanyid + psubComids;
        String[] arr = Util.TokenizerString2(psubComids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(subCompanyComInfo.getSubcompanyname(arr[i])).length() == 0) continue;
            if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
            returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewSubCompany(" + arr[i] + ");\" >" +
                    subCompanyComInfo.getSubcompanyname(arr[i]) + "</a>";
        }

        String pdeptids = "";
        pdeptids = getAllParentDepartId(deptid, pdeptids);
        pdeptids = deptid + pdeptids;
        arr = Util.TokenizerString2(pdeptids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(getDepartmentmark(arr[i])).length() == 0) continue;
            if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
            returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewDepartment(" + arr[i] + ");\" >" +
                    getDepartmentmark(arr[i]) + "</a>";
        }

        return returnStr;
    }

    public String getSSAllParentDepartmentMarks(String deptid, String subcomid) throws Exception {
        String returnStr = "";
        String subcompanyid = this.getSubcompanyid1(deptid);
        if (subcompanyid.length() == 0) subcompanyid = subcomid;
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String psubComids = "";
        psubComids = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid, psubComids);
        psubComids = subcompanyid + psubComids;
        String[] arr = Util.TokenizerString2(psubComids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(subCompanyComInfo.getSubcompanyname(arr[i])).length() == 0) continue;
            if (i == arr.length - 1) {
                if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
                returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewSubCompany(" + arr[i] + ");\" >" +
                        subCompanyComInfo.getSubcompanyname(arr[i]) + "</a>";
            }

        }

        String pdeptids = "";
        pdeptids = getAllParentDepartId(deptid, pdeptids);
        pdeptids = deptid + pdeptids;
        arr = Util.TokenizerString2(pdeptids, ",");
        for (int i = arr.length - 1; i >= 0; i--) {
            if (Util.null2String(getDepartmentmark(arr[i])).length() == 0) continue;
            if (i == 0) {
                if (returnStr.length() > 0) returnStr += "<span style=\"color:#B8B8B8;\">/</span>";
                returnStr += "<a href=\"javascript:void(0)\"  onclick=\"javascript:viewDepartment(" + arr[i] + ");\" >" +
                        getDepartmentmark(arr[i]) + "</a>";
            }
        }

        return returnStr;
    }

    /**
     * create by Eugene 2018.10.12
     * 获取部门全路径，用于数据导入
     *
     * @param deptid
     * @return
     * @throws Exception
     */
    public String getDepartmentRealPath(String deptid) throws Exception {
        String returnStr = "";
        try {
            String pdeptids = "";
            pdeptids = getAllParentDepartId(deptid, pdeptids);
            pdeptids = deptid + pdeptids;
            String[] arr = Util.TokenizerString2(pdeptids, ",");
            for (int i = arr.length - 1; i >= 0; i--) {
                if (Util.null2String(getDepartmentname(arr[i])).length() == 0) continue;
                if (returnStr.length() > 0) returnStr += ">";
                returnStr += getDepartmentname(arr[i]);
            }
        } catch (Exception e) {
            new BaseBean().writeLog("DepartmentComInfo>>>getDepartmentRealPath" + e);
        }
        return returnStr;
    }

    /**
     * create by Eugene 2019.3.8
     * 获取部门全路径，根据delimiter格式化
     *
     * @param deptid
     * @param delimiter
     * @return
     * @throws Exception
     */
    public String getDepartmentRealPath(String deptid, String delimiter, String orderType) throws Exception {
        String returnStr = "";
        List<String> names = new ArrayList<>();
        try {
            String pdeptids = "";
            pdeptids = getAllParentDepartId(deptid, pdeptids);
            pdeptids = deptid + pdeptids;
            String[] arr = Util.TokenizerString2(pdeptids, ",");
            for (String id : arr) {
                String name = getDepartmentmark(id);
                if (!"".equals(name)) {
                    names.add(name);
                }
            }
            if ("0".equals(orderType))
                Collections.reverse(names);
        } catch (Exception e) {
            new BaseBean().writeLog("DepartmentComInfo>>>getDepartmentRealPath" + e);
        }
        return String.join(delimiter, names);
    }

    public String getDepartmentRealPath(String deptid, String delimiter, String orderType, boolean includeSelf) throws Exception {
        String returnStr = "";
        List<String> names = new ArrayList<>();
        try {
            String pdeptids = "";
            pdeptids = getAllParentDepartId(deptid, pdeptids);
            pdeptids = deptid + pdeptids;
            String[] arr = Util.TokenizerString2(pdeptids, ",");
            for (String id : arr) {
                if (!includeSelf && id.equals(deptid))
                    continue;
                String name = getDepartmentname(id);
                if (!"".equals(name)) {
                    names.add(name);
                }
            }
            if ("0".equals(orderType))
                Collections.reverse(names);
        } catch (Exception e) {
            new BaseBean().writeLog("DepartmentComInfo>>>getDepartmentRealPath" + e);
        }
        return String.join(delimiter, names);
    }

    public String getDepartmentNames(String deptids) {
        String returnStr = "";
        String[] arr = Util.TokenizerString2(deptids, ",");
        for (int i = 0; i < arr.length; i++) {
            returnStr += getDepartmentname(arr[i]) + ",";
        }
        if (!"".equals(returnStr)) returnStr = returnStr.substring(0, returnStr.length() - 1);
        return returnStr;
    }

    public String getDepartmentName(String id) throws Exception {
        String departmentmark = this.getDepartmentmark(id);
        String caceled = Util.null2String(this.getDeparmentcanceled(id));
        if ("1".equals(caceled)) {
            departmentmark += "<span><font color=\"red\">(" + weaver.systeminfo.SystemEnv.getHtmlLabelName(22205, weaver.general.ThreadVarLanguage.getLang()) + ")</font></span>";
            //subCompanyName += "<span><font color=\"red\">("+SystemEnv.getHtmlLabelName(22205,user.getLanguage())+")</font></span>";
        }
        return departmentmark;
    }

    public ArrayList<String> getDepartmentOperate(String id, String canEdit, String otherPara) {
        ArrayList<String> resultList = new ArrayList<String>();
        String canCancel = otherPara.split(":")[0];
        String canIsCancel = otherPara.split(":")[0];
        String log = otherPara.split(":")[1];

        if (canEdit.equals("true")) {
            resultList.add("true");
        } else {
            resultList.add("false");
        }

        if (canCancel.equals("true")) {
            resultList.add(getDepartmentCanCancel(id));
        } else {
            resultList.add("false");
        }

        if (canIsCancel.equals("true")) {
            resultList.add(getDepartmentCanIsCancel(id));
        } else {
            resultList.add("false");
        }

        if (canEdit.equals("true")) {
            resultList.add("true");
            resultList.add("true");
            resultList.add("true");
        }

        if (log.equals("true")) {
            resultList.add("true");
        } else {
            resultList.add("false");
        }

        return resultList;
    }

    public String getDepartmentCanCancel(String id) {
        RecordSet rs = new RecordSet();
        String canceled = "";
        rs.executeSql("select canceled from HrmDepartment where id=" + id);
        if (rs.next()) {
            canceled = Util.null2String(rs.getString("canceled"));
        }
        if (canceled.equals("0") || canceled.equals("")) {
            return "true";
        } else {
            return "false";
        }
    }

    public String getDepartmentCanIsCancel(String id) {
        RecordSet rs = new RecordSet();
        String canceled = "";
        rs.executeSql("select canceled from HrmDepartment where id=" + id);
        if (rs.next()) {
            canceled = Util.null2String(rs.getString("canceled"));
        }
        if (canceled.equals("1")) {
            return "true";
        } else {
            return "false";
        }
    }

    public String getDepartmentCheckbox(String id) {
        RecordSet rs = new RecordSet();
        rs.executeSql("select * from hrmresource where departmentid= " + id);
        if (rs.next()) {//如果存在人员，则不能被删除
            return "false";
        }
        return "true";
    }

    //用于可编辑列表
    public String getDepartmentsForEdit(String deptIds) throws Exception {
        JSONArray jsa = new JSONArray();
        String deptNames = "";
        DepartmentComInfo comInfo = new DepartmentComInfo();
        String[] deptIdArrays = Util.TokenizerString2(deptIds, ",");
        for (int i = 0; deptIdArrays != null && i < deptIdArrays.length; i++) {
            String tempUserId = deptIdArrays[i];
            deptNames = comInfo.getDepartmentmark(tempUserId) + "&nbsp;";
            JSONObject json = new JSONObject();
            json.put("browserValue", tempUserId);
            json.put("browserSpanValue", deptNames);
            jsa.add(json);
        }
        return jsa.toString();
    }
}
